import {UserMenus} from "@/store/login/types";
import {RouteRecordRaw} from "vue-router";
import {YBreadcrumbProp} from "@/base-ui/breadcrumb/types";

export const mapMenusToRoutesAndPermissions =  async (menus: UserMenus[]): Promise<{ permissions: string[], routes: RouteRecordRaw[] }> => {
    const routes: RouteRecordRaw[] = [];
    const permissions: string[] = [];

    // 1. 先去加载所有的路由
    const allRoutes = await getAllRoutes();
    // 2。 根据菜单获得匹配的route
    // menu.type == 0 => getChildren
    // menu.type == 1 => getUrl => 匹配路由
    console.log("data", allRoutes)

    const _recurseGetRoute = (menus: UserMenus[]) => {
        for (const menu of menus) {
            if (menu.type == 1) {
                const route = allRoutes.find((route) => route.path === menu.url)
                if (route){
                    routes.push(route);
                }
                if (menu.children){
                    _recurseGetRoute(menu.children)
                }
            } else if (menu.type == 0 && menu.children) {
                _recurseGetRoute(menu.children)
            }else if (menu.type == 2 && menu.code){
                permissions.push(menu.code)
            }
        }
    }

    _recurseGetRoute(menus)


    return Promise.resolve({
        permissions: permissions,
        routes: routes
    });
}


async function getAllRoutes(): Promise<RouteRecordRaw[]> {
    const allRoutes: RouteRecordRaw[] = [];
    const routeFiles = import.meta.glob("../configs/routers/home/**/*.ts");

    for (let routeFilesKey in routeFiles) {
        let mod = await routeFiles[routeFilesKey]()
        console.log("mod", mod)
        allRoutes.push(mod.default)
        // @ts-ignore
    }

    return Promise.resolve(allRoutes)
}
export function pathMapBreadcrumbs(userMenus: any[], currentPath: string) {
    const breadcrumbs: YBreadcrumbProp[] = []
    pathMapToMenu(userMenus, currentPath, breadcrumbs)
    return breadcrumbs
}

export const pathMapToMenu = (userMenus:any[], currentPath?: string, breadcrumbs?: YBreadcrumbProp[], parentKeys?: string[]):any => {
    for(const menu of userMenus){
        if (menu.type === 0){
            const findMenu = pathMapToMenu(menu.children ?? [], currentPath)
            if (findMenu){
                breadcrumbs?.push({ name: menu.name, path: menu.url })
                breadcrumbs?.push({ name: findMenu.name, path: findMenu.url })
                parentKeys?.push("dir:" + menu.code)
                return findMenu;
            }
        }else if (menu.type == 1 && menu.url === currentPath){
            return menu;
        }
    }
}
